package bsc.war.handler;

import bsc.ejb.entity.DimensionalCut;
import bsc.ejb.entity.Map;
import bsc.ejb.entity.Person;
import bsc.ejb.entity.Project;
import bsc.ejb.entity.SRM;
import bsc.ejb.entity.ScoreCard;
import bsc.ejb.entity.ScoreDomain;
import bsc.ejb.entity.ScoreView;
import bsc.ejb.metadata.Colorimetry;
import bsc.ejb.metadata.Comparation;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import bsc.war.model.Score;
import bsc.war.service.ScoreCardUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author Memo
 */
public class MainFinalUser extends AbstractController {

    public MainFinalUser() {
    }

    @Override
    protected ModelAndView handleRequestInternal(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");
            ScoreDomain currentSD = (ScoreDomain) request.getSession().getAttribute("currentScoreDomain");
            ScoreView currentView = currentSD.getScoreView();

            HttpSession session = request.getSession(true);
            Person person = (Person) session.getAttribute("person");
            /*
            List<Map> mapList = delegate.findMap();
            List<Map> maps2remove = new Linked  List<Map>();
            for(Map tmp : mapList)
            if( !tmp.getScoreview().equals(currentView) )
            maps2remove.add(tmp);
            for(Map tmp : maps2remove)
            mapList.remove(tmp);
            request.setAttribute("mapList", mapList);
             */

            List<Map> mapList = new ArrayList<Map>();
            mapList.add((Map) currentView.getScoreCard());
            request.setAttribute("mapList", mapList);

            List<SRM> srmList = delegate.findSRM();
            List<SRM> srms2remove = new LinkedList<SRM>();
            for (SRM tmp : srmList) {
                if (!tmp.getScoreView().equals(currentView)) {
                    srms2remove.add(tmp);
                }
            }
            for (SRM tmp : srms2remove) {
                srmList.remove(tmp);
            }
            request.setAttribute("srmList", srmList);

            List<Project> projectList = delegate.findProject(person);

            request.setAttribute("projectList", projectList);

            List<ScoreView> scoreViewList = new ArrayList<ScoreView>(); //delegate.findScoreView();
            scoreViewList.add(currentView);
            request.setAttribute("scoreViewList", scoreViewList);

            List<Comparation> comparationList = new ArrayList<Comparation>();
            List<Comparation> comparations = delegate.findComparation(delegate.findFramework(true), true);
            for (Comparation comparation : comparations) {
                if (comparation.getType() != comparation.getType().REAL) {
                    comparationList.add(comparation);
                }
            }
            request.setAttribute("comparationList", comparationList);

            //Date date = request.getSession().getAttribute("date") == null ? ScoreCardUtils.getLastDate() : (Date)request.getSession().getAttribute("date");
            //Comparation comparation = request.getSession().getAttribute("comparation") == null ? delegate.findComparation(2L) : (Comparation)request.getSession().getAttribute("comparation");

            Date date = ScoreCardUtils.getSystemDate(request);
            Comparation comparation = ScoreCardUtils.getSystemComparation(request);


            session.setAttribute("date", date);
            session.setAttribute("comparation", comparation);

            ScoreCard parentScorecard = request.getParameter("rootScoreCard") != null && request.getParameter("rootScoreCard").length() > 0 ? delegate.findScoreCard(Long.parseLong(request.getParameter("rootScoreCard"))) : scoreViewList.get(0).getScoreCard();




            // if is root of scorecard tree
            if (parentScorecard.getScoreview() != null) {
                session.setAttribute("scoreCardView", parentScorecard);
            }

            //DEBUG
            //System.out.println("Calculando: " + parentScorecard.getName());

            Score score = ScoreCardUtils.calculateScore(delegate, comparation, parentScorecard, date);
            Double weightScoreCard = 1D;


            Colorimetry colorimetry = delegate.findColorimetry(parentScorecard, score.getScore());

            // System.out.println("score.isOutOfDay: " + score.isOutOfDate());

            //Update members of all dimensional cuts
            //List of all DimensionalCuts
            List<DimensionalCut> dimensionalCuts = ScoreCardUtils.getDimensionalCuts(request, delegate);

            //Se obtiene los strings de los cuts
            java.util.Map<DimensionalCut, String> dimensionalCutsMembers = ScoreCardUtils.getDimensionalCutsMembersStrings(request, delegate, dimensionalCuts);


            request.setAttribute("parentScore", score);
            request.setAttribute("parentScoreColor", colorimetry == null ? "" : colorimetry.getColor());
            request.setAttribute("currentPeriod", date);
            request.setAttribute("parentScorecard", parentScorecard);
            request.setAttribute("childrenCount", new Integer(delegate.findScoreCard(parentScorecard).size()));
            request.setAttribute("weightScoreCard", weightScoreCard);
            request.setAttribute("dimensionalCutsMembers", dimensionalCutsMembers);

            // BACKLINK
            if (request.getParameter("mapId") != null && request.getParameter("mapId").length() > 0) {
                request.setAttribute("backlink", "mapFinalUser.do?map=" + request.getParameter("mapId"));
            } else if (request.getParameter("srmId") != null && request.getParameter("srmId").length() > 0) {
                request.setAttribute("backlink", "mapFinalUser.do?map=" + request.getParameter("mapId"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Catched exception", e);
        }
        return new ModelAndView("mainFinalUser");
    }
}
